import os
import queue
from datetime import datetime

from PySide2.QtWidgets import QFileDialog, QMessageBox
from src.lib.errorno import g_errno_d
from src.lib.thread_stop import stop_thread
from src.lib.find_file import search_file
    
class FactoryBurn():

    def __init__(self, ui, port):
        self.ui = ui
        self.Port = port
        self.MainWindow = self.ui.MainWindow

    # 投递文本到[调试接收框]
    def uiForwardReceive(self, text):
        self.Port.sendTextToReceive(self.Port.Page['DEBUG'].value, text)

    def uiJlinkFindFile(self):
        text = search_file("JLink.exe")
        if text != "":
            text = text.replace("JLink.exe", "")
            text = text.replace("\\", "/")
            if text[-1] != "/":
                text += "/"
            self.MainWindow.le_jlinkFilePath.setText(text)

    def uiReadJlinkFile(self):
        file_name = []
        file_path = self.MainWindow.le_jlinkFilePath.text()
        file_name = QFileDialog.getExistingDirectory(self.ui, "选择目录", file_path)
        print(file_name)
        if len(file_name) > 0:
            text = text.replace("\\", "/")
            if file_name[-1] != "/":
                file_name += "/"
            self.MainWindow.le_jlinkFilePath.setText(file_name)

    def uiReadJlinkBurnFile(self):
        file_name = []
        file_path = os.path.dirname(self.MainWindow.le_jlinkBurnFilePath.text())
        if os.path.isdir(file_path):
            path = file_path
        else:
            path = "/"
        file_name = QFileDialog.getOpenFileName(self.ui, "选择文件", path, "Bin File(*.bin);;Hex File(*.hex)")
        if len(file_name[0]) > 0:
            self.MainWindow.le_jlinkBurnFilePath.setText(file_name[0])

    def uiStartJlinkBurnFile(self):
        if os.path.exists('./Burn/'):
            print('exist')
        else:
            os.mkdir('./Burn/')  #创建
        file_handle = open('./Burn/download.bat', mode='w+')
        file_handle.write('set PATH='+ self.MainWindow.le_jlinkFilePath.text() +'; \n')
        file_handle.write('JLink.exe -autoconnect 1 -device ' + self.MainWindow.cmb_jlinkChipType.currentText() + ' -if swd -speed 4000 -commandfile .\\Burn\\download.jlink')
        file_handle.close()
        file_handle = open('./Burn/download.jlink', mode='w+')
        file_handle.write('reset\nerase\n')
        file_handle.write('loadfile ' + self.MainWindow.le_jlinkBurnFilePath.text() + ' ' + self.MainWindow.le_jlinkBurnAddr.text() + ' \n')
        if self.MainWindow.chk_jlinkChipLock.isChecked():
            file_handle.write("\nSecureArea Create\n")
        file_handle.write('r\nqc\n')
        file_handle.close()
        os.system("cmd.exe /c .\\Burn\\download.bat > .\\Burn\\log.txt")

    def uiUnJlinkLock(self):
        if os.path.exists('./Burn/'):
            print('exist')
        else:
            os.mkdir('./Burn/')  #创建
        file_handle = open('./Burn/unlock.bat', mode='w+')
        file_handle.write('set PATH='+ self.MainWindow.le_jlinkFilePath.text() +'; \n')
        file_handle.write('JLink.exe -autoconnect 1 -device ' + self.MainWindow.cmb_jlinkChipType.currentText() + ' -if swd -speed 4000 -commandfile .\\Burn\\unlock.jlink')
        file_handle.close()
        file_handle = open('./Burn/unlock.jlink', mode='w+')
        file_handle.write('unlock kinetis\nSecureArea Remove\n')
        file_handle.write('reset\nerase\n')
        file_handle.write('r\nqc\n')
        file_handle.close()
        os.system("cmd.exe /c .\\Burn\\unlock.bat > .\\Burn\\log_unlock.txt")

    def uiSTlinkFindFile(self):
        text = search_file("ST-LINK_CLI.exe")
        if text != "":
            text = text.replace("ST-LINK_CLI.exe", "")
            text = text.replace("\\", "/")
            if text[-1] != "/":
                text += "/"
            self.MainWindow.le_stlinkFilePath.setText(text)

    def uiReadSTlinkFile(self):
        file_name = []
        file_path = self.MainWindow.le_stlinkFilePath.text()
        file_name = QFileDialog.getExistingDirectory(self.ui, "选择目录", file_path)
        print(file_name)
        if len(file_name) > 0:
            text = text.replace("\\", "/")
            if file_name[-1] != "/":
                file_name += "/"
            self.MainWindow.le_stlinkFilePath.setText(file_name)

    def uiReadSTlinkBurnFile(self):
        file_name = []
        file_path = os.path.dirname(self.MainWindow.le_stlinkBurnFilePath.text())
        if os.path.isdir(file_path):
            path = file_path
        else:
            path = "/"
        file_name = QFileDialog.getOpenFileName(self.ui, "选择文件", path, "Bin File(*.bin);;Hex File(*.hex)")
        if len(file_name[0]) > 0:
            self.MainWindow.le_stlinkBurnFilePath.setText(file_name[0])

    def uiStartSTlinkBurnFile(self):
        if os.path.exists('./Burn/'):
            print('exist')
        else:
            os.mkdir('./Burn/')  #创建
        file_handle = open('./Burn/st_download.bat', mode='w+')
        # file_handle.write('set PATH='+ self.MainWindow.le_stlinkFilePath.text() +'; \n')
        file_handle.write('set p0='+ self.MainWindow.le_stlinkBurnFilePath.text() +'; \n')
        file_handle.write('ST-LINK_CLI -c SWD UR -Rst -ME -P %p0% ' + self.MainWindow.le_stlinkBurnAddr.text() + ' -V -Rst -Run ' + self.MainWindow.le_stlinkBurnAddr.text())
        file_handle.close()
        os.system("cmd.exe /c .\\Burn\\st_download.bat > .\\Burn\\st_log.txt")
